package logger

import (
	"io"
	"log"
	"os"

	formatter "github.com/antonfisher/nested-logrus-formatter"
	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
)

var (
	Log1   *logrus.Logger
	AppLog *logrus.Entry
	CfgLog *logrus.Entry
)

var (
	LogDir            string = "/var/log/nd/"
	MaxSizeDefault    int    = 50   // Max MB before log is rotated
	MaxBackupsDefault int    = 10   // Max number of old log files to keep
	MaxAgeDefault     int    = 3650 // Max number of days to retain log files
)

func init() {

	if err := os.MkdirAll(LogDir, 0775); err != nil {
		log.Printf("Mkdir %s failed: %+v", LogDir, err)
	}

	Log1 = logrus.New()
	Log1.SetReportCaller(false)
	Log1.Formatter = &formatter.Formatter{
		TimestampFormat: "2006-01-02 15:04:05.000",
		TrimMessages:    true,
		NoFieldsSpace:   true,
		HideKeys:        true,
		NoColors:        true,
		FieldsOrder:     []string{"component", "category", "subcategory"},
	}
	ljlogrotate1 := &lumberjack.Logger{
		Filename:   LogDir + "nd-app.log",
		MaxSize:    MaxSizeDefault,
		MaxBackups: MaxBackupsDefault,
		MaxAge:     MaxAgeDefault,
	}
	Log1.SetOutput(io.MultiWriter(os.Stdout, ljlogrotate1))
	AppLog = Log1.WithFields(logrus.Fields{"component": "APP"})
	CfgLog = Log1.WithFields(logrus.Fields{"component": "CFG"})
}

func SetLogLevel(level string) {
	lvl, err := logrus.ParseLevel(level)
	if err != nil {
		AppLog.Fatalln("Failed to parse log level:", err)
	}
	Log1.SetLevel(lvl)
}
